'use strict';

const Controller = require('egg').Controller;
const Res = require('../utils/response');
const joi = require("joi")

class UsersController extends Controller {
  async getUser() {
    const {
      ctx
    } = this;
    const schema = {
      username: joi.string().error(new Error("账户名格式不正确")),
      nickname: joi.string().error(new Error("用户名格式不正确")),
    }
    const {
      error,
      value
    } = joi.validate(ctx.request.body, schema);
    if (error) {
      ctx.status = 201;
      ctx.body = Res(201, error.toString(), '操作失败');
      return;
    }
    const result = await ctx.model.Users.findAll({
      where: {
        username: {
          $like: `%${value&&value.username || ''}%`
        },
        nickname: {
          $like: `%${value&&value.nickname || ''}%`
        }
      }
    });
    ctx.body = Res(0, result);
  }

  async login() {
    const ctx = this.ctx;
    const schema = {
      username: joi.string().min(2).max(6).required().error(new Error("账户名格式不正确")),
      password: joi.string().regex(/^[a-zA-Z0-9]+$/).required().error(new Error("密码格式不正确")),
    }
    const {
      error,
      value
    } = joi.validate(ctx.request.body, schema);
    if (error) {
      ctx.status = 201;
      ctx.body = Res(201, error.toString(), '操作失败');
      return;
    }
    const hasUser = await ctx.model.Users.findAll({
      where: {
        username: value.username,
        password: value.password
      }
    });

    if (hasUser.length > 0) {
      ctx.body = Res(0, result, '成功了');
    } else {
      ctx.body = Res(201, result, '用户不存在');
    }
  }

  // 注册
  async register() {
    const {
      ctx
    } = this;
    console.log('进入到了注册', ctx.request.body);
    // 定义验证规则
    const schema = {
      username: joi.string().min(2).max(20).required().error(new Error("账户名格式不正确")),
      nickname: joi.string().min(2).max(20).required().error(new Error("用户名格式不正确")),
      password: joi.string().regex(/^[a-zA-Z0-9]+$/).required().error(new Error("密码格式不正确")),
      desc: joi.string().error(new Error("介绍格式不正确")),
      cover: joi.string().error(new Error("图片路径有误"))
    }
    const {
      error,
      value
    } = joi.validate(ctx.request.body, schema);
    if (error) {
      ctx.status = 201;
      ctx.body = Res(201, error.toString(), '报错了');
      return;
    }
    const result = await ctx.model.Users.create(value);
    ctx.body = Res(0, result);
  }
}

module.exports = UsersController;